import grails.test.ControllerUnitTestCase

class TradeControllerTests extends ControllerUnitTestCase{

    def controller
    Trade trade1, trade2

    void setUp(){
        super.setUp()
        controller = new TradeController()
        trade1 = new Trade(tradeName:'plumber')
        trade2 = new Trade(tradeName:'carpenter')

        mockDomain Trade, [trade1, trade2]
    }

    void testThatOneItemIsReturnedForSearchAjax() {
        controller.params.query = 'pl'
        controller.searchAjax()
        assertEquals('text/xml', renderArgs.contentType)
        def results = new XmlParser().parseText(mockResponse.content.toString())

        def allResults = results.result
        assertEquals( 1, allResults.size())
        assertEquals( trade1.tradeName, allResults[0].name.text())
    }

    void testThatTwoItemsAreReturnedForSearchAjax() {
        controller.params.query = 'p'
        controller.searchAjax()
        assertEquals('text/xml', renderArgs.contentType)
        def results = new XmlParser().parseText(mockResponse.content.toString())

        def allResults = results.result
        assertEquals( 2, allResults.size())
        assertEquals( trade1.tradeName, allResults[0].name.text())
        assertEquals( trade2.tradeName, allResults[1].name.text())
    }

    void testThatNothingIsReturned() {
        controller.params.query = 'z'
        controller.searchAjax()
        assertEquals('text/xml', renderArgs.contentType)
        def results = new XmlParser().parseText(mockResponse.content.toString())

        def allResults = results.result
        assertEquals( 0, allResults.size())
    }

    void testThatAllResultsAreReturnedForEmptyString(){
        controller.params.query = ''
        controller.searchAjax()
        assertEquals('text/xml', renderArgs.contentType)
        def results = new XmlParser().parseText(mockResponse.content.toString())

        def allResults = results.result
        assertEquals( 2, allResults.size())
        assertEquals( trade1.tradeName, allResults[0].name.text())
        assertEquals( trade2.tradeName, allResults[1].name.text())
    }
}